//
//  UIImage+Orientation.m
//  YuanXinCamera
//
//  Created by GJS on 2018/5/18.
//  Copyright © 2018年 晏德智. All rights reserved.
//

#import "UIImage+Orientation.h"

@implementation UIImage (Orientation)

- (UIImage *)normalizedImage {
    if (self.imageOrientation == UIImageOrientationUp) return self;
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    [self drawInRect:(CGRect){0, 0, self.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

-(UIImage *)fixOrientation {
    
    // No-op if the orientation is already correct
    if (self.imageOrientation == UIImageOrientationUp) return self;
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx ;//
    //    CGContextConcatCTM(ctx, transform);
    
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            ctx = CGBitmapContextCreate(NULL,self.size.height, self.size.width,
                                        CGImageGetBitsPerComponent(self.CGImage), 0,
                                        CGImageGetColorSpace(self.CGImage),
                                        CGImageGetBitmapInfo(self.CGImage));
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
            break;
            
        default:
            ctx = CGBitmapContextCreate(NULL,self.size.width, self.size.height,
                                        CGImageGetBitsPerComponent(self.CGImage), 0,
                                        CGImageGetColorSpace(self.CGImage),
                                        CGImageGetBitmapInfo(self.CGImage));
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

@end
